package com.sanglh.tutorial.common.util;

import java.lang.reflect.Method;
import java.util.ArrayList;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.sanglh.tutorial.common.base.Logging;
import com.sanglh.tutorial.common.base.SimInfo;

public class SIMUtils {
	// =========================================================================================================
	public static ArrayList<SimInfo> getAllSims(Context context) {
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		ArrayList<SimInfo> sims = new ArrayList<SimInfo>();
		// SIM 0
		SimInfo sim0 = new SimInfo();
		sim0.serial = telephonyManager.getSimSerialNumber();
		sim0.number = telephonyManager.getLine1Number();
		// SIM 1
		SimInfo sim1 = new SimInfo();
		Class<?> telephonyManagerClass = telephonyManager.getClass();

		try {
			Method getSimSerialNumberGemini = telephonyManagerClass
					.getDeclaredMethod("getSimSerialNumberGemini", Integer.TYPE);
			getSimSerialNumberGemini.setAccessible(true);
			sim1.serial = (String) getSimSerialNumberGemini.invoke(
					telephonyManager, 1);
			Method getLine1NumberGemini = telephonyManagerClass
					.getDeclaredMethod("getLine1NumberGemini", Integer.TYPE);
			getLine1NumberGemini.setAccessible(true);
			sim1.number = (String) getLine1NumberGemini.invoke(
					telephonyManager, 1);

		} catch (Throwable e) {
			Logging.log(e);
		}
		try {
			Method getSimSerialNumberDs = telephonyManagerClass
					.getDeclaredMethod("getSimSerialNumberDs", Integer.TYPE);
			getSimSerialNumberDs.setAccessible(true);
			sim1.serial = (String) getSimSerialNumberDs.invoke(
					telephonyManager, 1);
			Method getLine1NumberDs = telephonyManagerClass.getDeclaredMethod(
					"getLine1NumberDs", Integer.TYPE);
			getLine1NumberDs.setAccessible(true);
			sim1.number = (String) getLine1NumberDs.invoke(telephonyManager, 1);
		} catch (Throwable e) {
			Logging.log(e);
		}
		if (!TextUtils.isEmpty(sim0.serial)) {
			sim0.label = "Current SIM";
			sims.add(sim0);
		}
		if (!TextUtils.isEmpty(sim1.serial)) {
			sim1.label = "SIM 2";
			sims.add(sim1);
			if (!TextUtils.isEmpty(sim0.serial)) {
				sim0.label = "SIM 1";
			}
		}

		return sims;
	}

}
